#include "Model3D.h"
#include "TextureLoader.h"

Model3D::Model3D(void)
{
}

Model3D::~Model3D(void)
{
}

bool Model3D::load(string modelName, string textureName)
{
	Assimp::Importer importer;
	const aiScene * scene = importer.ReadFile(modelName,aiProcessPreset_TargetRealtime_Fast);

	if (!scene)
	{
		cout << "ERROR : Cannot open \"" << modelName << "\"\n";
		return false;
	}

	mesh = scene->mMeshes[0];

	numTriangles = mesh->mNumFaces * 3;
	int index = 0;
 
	vertexArray = new float[mesh->mNumFaces * 3 * 3];
	uvArray = new float[mesh->mNumFaces * 3 * 2];
 
	for(unsigned int i=0; i < mesh->mNumFaces; i++)
	{
		const aiFace& face = mesh->mFaces[i];

		for (int j=0; j < 3; j++)//assume all faces are triangulated
		{
			aiVector3D uv = mesh->mTextureCoords[0][face.mIndices[j]];
			memcpy(uvArray, &uv, sizeof(float)*2);
			uvArray += 2;
 
			aiVector3D pos = mesh->mVertices[face.mIndices[j]];
			memcpy(vertexArray, &pos, sizeof(float)*3);
			vertexArray += 3;
		}
	}
 
	uvArray -= mesh->mNumFaces * 3 * 2;
	vertexArray -= mesh->mNumFaces * 3 * 3;

	texId = TextureLoader::instance()->loadTexture(textureName);

	if (texId == 0)
	{
		cout << "ERROR : Cannot open \"" << textureName << "\"\n";
		return false;
	}

	return true;
}

void Model3D::render()
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texId);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 
	glVertexPointer(3, GL_FLOAT, 0, vertexArray);

	glTexCoordPointer(2, GL_FLOAT, 0, uvArray);
 
	glDrawArrays(GL_TRIANGLES, 0, numTriangles);
 
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisable(GL_TEXTURE_2D);
}
